"""
Authors:    Jingjing WU (吴京京) <https://github.com/wj-Mcat>

2020-now @ Jingjing Wu
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import annotations

from torch import Tensor
from src.config import Distance


def compute_distance(query: Tensor, support_set: Tensor, distance: Distance, epsilon: float):
    """
    compute distance between query & support set by different distance function
    Args:
        query: user query
        support_set: the class proto types of support set
        distance: distance method
        epsilon: the distance of the

    Returns: the final distance function

    """
    query_n, query_dim = query.shape
    support_n, support_dim = support_set.shape

    if distance == Distance.l2:
        distances = (
                query.unsqueeze(1).expand(query_n, support_n, -1) -
                support_set.unsqueeze(0).expand(query_n, support_n, -1)
        ).pow(2).sum(dim=2)
        return distances

    elif distance == Distance.cosine:
        normalised_x = query / (query.pow(2).sum(dim=1, keepdim=True).sqrt() + epsilon)
        normalised_y = support_set / (support_set.pow(2).sum(dim=1, keepdim=True).sqrt() + epsilon)

        expanded_x = normalised_x.unsqueeze(1).expand(query_n, support_n, -1)
        expanded_y = normalised_y.unsqueeze(0).expand(query_n, support_n, -1)

        cosine_similarities = (expanded_x * expanded_y).sum(dim=2)
        return 1 - cosine_similarities
    elif distance == Distance.dot:
        expanded_x = query.unsqueeze(1).expand(query_n, support_n, -1)
        expanded_y = support_set.unsqueeze(0).expand(query_n, support_n, -1)

        return -(expanded_x * expanded_y).sum(dim=2)
    else:
        raise (ValueError('Unsupported similarity function'))
